package com.xiaoran.client.proxy;

import com.xiaoran.client.config.ClientValue;
import com.xiaoran.common.annotation.RpcClient;
import com.xiaoran.common.utils.SpringBeanFactory;
import org.apache.commons.collections.CollectionUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Set;
//动态代理管理器
@Component
public class ServiceProxyManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProxyManager.class);

    @Autowired
    private ClientValue  clientValue;
    @Autowired
    private ProxyHelper proxyHelper;
    
    public void initServiceProxyInstance() {
        Reflections reflections = new Reflections(clientValue.getRpcClientApiPackage());
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcClient.class);
        if (CollectionUtils.isEmpty(typesAnnotatedWith)) {
            return;
        }
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) SpringBeanFactory.context().getAutowireCapableBeanFactory();
        for (Class<?> cls : typesAnnotatedWith) {
            String name = cls.getName();
            beanFactory.registerSingleton(name,proxyHelper.newProxyInstance(cls));
        }
        LOGGER.info("Initialize proxy for service successfully");

    }
}
